package ospf

import (
	"encoding/binary"
	"fmt"
	"github.com/google/gopacket"
)

// DecodeFromBytes 实现解码方法
func (o *OSPFv2) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
	if len(data) < OSPFv2HeaderLength {
		return fmt.Errorf("OSPF packet too short")
	}

	o.Version = data[0]
	o.Type = data[1]
	o.PacketLength = binary.BigEndian.Uint16(data[2:4])
	o.RouterID = binary.BigEndian.Uint32(data[4:8])
	o.AreaID = binary.BigEndian.Uint32(data[8:12])
	o.Checksum = binary.BigEndian.Uint16(data[12:14])
	o.AuType = binary.BigEndian.Uint16(data[14:16])
	o.Authentication = binary.BigEndian.Uint64(data[16:24])

	o.Contents = data[:OSPFv2HeaderLength]
	o.Payload = data[OSPFv2HeaderLength:]

	return nil
}

func (h *OSPFv2Hello) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
	if len(data) < HelloPacketMinLength {
		return fmt.Errorf("OSPF Hello packet too short")
	}

	h.NetworkMask = binary.BigEndian.Uint32(data[0:4])
	h.HelloInterval = binary.BigEndian.Uint16(data[4:6])
	h.Options = data[6]
	h.Priority = data[7]
	h.DeadInterval = binary.BigEndian.Uint32(data[8:12])
	h.DR = binary.BigEndian.Uint32(data[12:16])
	h.BDR = binary.BigEndian.Uint32(data[16:20])

	remainingBytes := len(data) - HelloPacketMinLength
	if remainingBytes > 0 && remainingBytes%4 == 0 {
		neighborCount := remainingBytes / 4
		h.Neighbors = make([]uint32, neighborCount)
		for i := 0; i < neighborCount; i++ {
			offset := HelloPacketMinLength + (i * 4)
			h.Neighbors[i] = binary.BigEndian.Uint32(data[offset : offset+4])
		}
	}

	h.Contents = data
	h.Payload = nil

	return nil
}
